<template>
  <div class="member-detail">
    <!-- 基本信息 -->
    <el-card class="box-card">
      <div slot="header">
        <span>基本信息</span>
      </div>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="姓名">{{ materials.realname }}</el-descriptions-item>
        <el-descriptions-item label="昵称">{{ orderInfo.customerName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ orderInfo.contactPhone }}</el-descriptions-item>
        <el-descriptions-item label="签证名称">{{ orderInfo.productName }}</el-descriptions-item>
        <el-descriptions-item label="材料状态">{{ orderInfo.materialStatus }}</el-descriptions-item>
        <el-descriptions-item label="签证状态">{{ orderInfo.visaStatus }}</el-descriptions-item>
        <el-descriptions-item label="订单号">{{ orderInfo.number }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 申请表栏位 -->
    <el-card class="box-card" style="margin-top: 20px;">
      <div slot="header">
        <span>申请表栏位</span>
      </div>
      <el-table :data="formFields" border style="width: 100%">
        <el-table-column prop="type" label="材料类型" width="180"/>
        <el-table-column prop="fieldCount" label="字段数量" width="180"/>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="handleView(scope.row, 'form')">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 申请材料栏位 -->
    <el-card class="box-card" style="margin-top: 20px;">
      <div slot="header">
        <span>申请材料栏位</span>
      </div>
      <el-table :data="materialFields" border style="width: 100%">
        <el-table-column prop="type" label="材料类型" width="180"/>
        <el-table-column prop="fieldCount" label="字段数量" width="180"/>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="handleView(scope.row, 'material')">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 材料状态确认 -->
    <el-card class="box-card" style="margin-top: 20px;">
      <div slot="header">
        <span>材料状态确认</span>
      </div>
      <div style="display: flex; align-items: center;">
        <el-select v-model="materialStatus" style="width: 200px; margin-right: 20px;">
          <el-option label="待确认" value="待确认"/>
          <el-option label="已确认" value="已确认"/>
        </el-select>
        <el-button type="primary" @click="confirmMaterialStatus">确认修改</el-button>
      </div>
    </el-card>
    <!-- 统一的查看弹窗 -->
    <el-dialog :title="currentType + '详情'" :visible.sync="dialogVisible" width="50%">
      <el-descriptions :column="1" border>
        <el-descriptions-item v-for="(value, key) in currentFields" :key="key" :label="key">
          <!-- 判断是否为图片类型 -->
          <template v-if="isImageField(value)">
            <el-image 
              :src="getImageUrl(value)" 
              :preview-src-list="[getImageUrl(value)]"
              fit="contain"
              style="max-width: 100%; max-height: 300px;">
            </el-image>
          </template>
          <template v-else>
            {{ value }}
          </template>
        </el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from '@/utils/request'

export default {
    data() {
        return {
            materials: {
                realname: ''
            },
            orderInfo: {
                customerName: '',
                contactPhone: '',
                productName: '',
                materialStatus: '',
                visaStatus: '',
                number: ''
            },
            materialStatus: '',
            formFields: [],
            materialFields: [],
            dialogVisible: false,
            currentType: '',
            currentFields: {}
        }
    },
    methods: {
        async fetchData(type) {
            try {
                // 使用订单号作为orderId
                const orderId = this.orderInfo.number;
                const res = await axios.get(`/admin/formUserMateri/vue/${orderId}`);
                if (res.data) {
                    // 根据 material_category 分类数据
                    const fields = res.data.map(item => ({
                        type: item.type,
                        fieldCount: Object.keys(item.fields).length,
                        fields: item.fields,
                        material_category: item.material_category
                    }));
                    
                    // 分别设置申请表和电子材料数据
                    this.formFields = fields.filter(item => item.material_category === 1);
                    this.materialFields = fields.filter(item => item.material_category === 0);
                }
            } catch (error) {
                console.error(`获取${type}数据失败：`, error);
                this.$message.error(`获取${type}数据失败`);
            }
        },

        // 添加判断是否为图片字段的方法
        isImageField(value) {
            // 判断值是否为图片文件名（根据常见图片扩展名）
            if (typeof value === 'string') {
                const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp'];
                return imageExtensions.some(ext => value.toLowerCase().endsWith(ext));
            }
            return false;
        },

        // 添加获取图片URL的方法
        getImageUrl(filename) {
            // 如果filename已经是完整的URL（以http开头），直接返回
            if (filename.startsWith('http')) {
                return filename;
            }
            // 否则拼接基础URL
            return `${process.env.VUE_APP_BASE_API}/images/usermaterial/${filename}`;
        },

        handleView(row, type) {
            this.currentType = row.type;
            this.currentFields = row.fields;
            this.dialogVisible = true;
        },

        handleEdit(row, type) {
            console.log(`编辑${type}：`, row);
        },
        async confirmMaterialStatus() {
            try {
                await this.$confirm('是否确认修改材料状态？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });
        
                // 发送更新请求
                const res = await axios.put('/admin/order/material-status', {
                    id: this.$route.params.id,  // 使用路由参数中的 id
                    materialStatus: this.materialStatus
                });
        
                // 更新成功
                this.$message.success('材料状态更新成功');
                // 更新本地显示的状态
                this.orderInfo.materialStatus = this.materialStatus;
                
                // 返回上一页
                this.$router.go(-1);
                
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('完整错误信息：', error.response || error);
                    this.$message.error('更新失败');
                }
            }
        }
    },
    async created() {
        // 获取路由参数
        this.materials.realname = this.$route.query.realname || ''; 
        this.orderInfo.customerName = this.$route.query.customerName || '';
        this.orderInfo.contactPhone = this.$route.query.contactPhone || '';
        this.orderInfo.productName = this.$route.query.productName || '';
        this.orderInfo.materialStatus = this.$route.query.materialStatus || '';
        this.orderInfo.visaStatus = this.$route.query.visaStatus || '';
        this.orderInfo.number = this.$route.query.number || '';

        // 获取表单和材料数据
        await Promise.all([
            this.fetchData('form'),
            this.fetchData('material')
        ]);
    },
}
</script>

<style>
.member-detail {
    padding: 20px;
}
.el-descriptions-item__label {
    width: 120px;
}
/* 添加图片容器样式 */
.el-descriptions-item__content img {
    display: block;
    margin: 10px 0;
    border: 1px solid #eee;
}
</style>